#!/bin/sh

# Copyright (C) 2016  Desktopd Developers.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


cd "`dirname "$0"`"

configPath="./config"
[ -f "$configPath" ] || {
	printf "No such configuration file: %s\n" "$configPath"
	exit 1
}

. "$configPath"

[ "$cloudflareAuthEmail" ] && [ "$cloudflareAuthKey" ] || {
	printf "Invalid configuration file: %s\n" "$configPath"
	exit 1
}

dataDir="./data"
exitListPath="${dataDir}/exit-list"
exitListCachePath="${dataDir}/exit-list.cache"
whitelistDBDir="${dataDir}/whitelist-db"

version='1.0'
faqURI='https://www.torproject.org/docs/faq-abuse.html.en'
curlUserAgent="Mozilla/5.0 (compatible; ExitWhitelister/${version}; +${faqURI})"

cloudflareEndpointAPI='https://api.cloudflare.com/client/v4'


# Whitelist ID
removeWhitelistById () {
	# DELETE
	curl \
		-A "$curlUserAgent" \
		-H "X-Auth-Email: ${cloudflareAuthEmail}" \
		-H "X-Auth-Key: ${cloudflareAuthKey}" \
		-X DELETE \
		"${cloudflareEndpointAPI}/user/firewall/access_rules/rules/${1}"
}


for path in "$whitelistDBDir"/*
do [ -f "$path" ] || continue
	id="`cat "$path"`"
	[ "$id" ] || continue
	echo "Removing the rule for $id (`basename "$path"`)..."
	removeWhitelistById "$id" >/dev/null || {
		removeWhitelistById "$id"
		echo
		echo "!!! Failed!"
	}
	sleep 0.1
done

# vim: set ts=4 noet ai
